import { createLoading } from '@/components/basics/BeLoading'
import { EnvConfig } from '@/config'
import { useUserStoreWithOut } from '@/stores/modules/user'
import { message } from 'ant-design-vue'
import { Request } from './request'

export * from './type'

const loading = createLoading()
// 默认http
const http = new Request(
  { baseURL: EnvConfig.getInstance().apiUrl },
  {
    loadingFlag: false,
    openLoad: () => {
      loading?.open()
    },
    closeLoad: () => {
      loading?.close()
    }
  }
)

const setupInterceptors = () => {
  const userStore = useUserStoreWithOut()
  // 请求拦截
  http.getAxiosInstance().interceptors.request.use(
    (config) => {
      // token处理，正式环境使用了sessions和cookie登录，开发写死一个token
      const token = userStore.getToken()
      if (token && !EnvConfig.getInstance().isProd) config.headers.Authorization = `Bearer ${token}`
      // 租户处理
      const tenant = userStore.getTenant()
      if (tenant) config.headers['x-unify-tenant-code'] = tenant
      return config
    },
    (error) => {
      // 请求错误处理
      return Promise.reject(error)
    }
  )

  // 响应拦截
  http.getAxiosInstance().interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      const requestOptions = error.config?.requestOptions || {}
      // 全局提示
      if (requestOptions.globAlToast && error.response) {
        message.error(error.response.details || '请求失败')
      }
      // 超时
      if (error.message.includes('timeout')) {
        message.error('请求超时')
      }
      return Promise.reject(error)
    }
  )
}

setupInterceptors()

export { http, Request }
